package com.fy.controller;

import com.fy.config.FileConfig;
import com.fy.entity.EpcUser;
import com.fy.entity.PageEntity;
import com.fy.entity.TreeEntity;
import com.fy.service.EpcUserService;
import com.fy.service.GroupService;
import com.fy.utils.TreeNodeUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("epc")
@CrossOrigin
public class EpcUserController extends BaseController {
	private static final Logger logger = LoggerFactory.getLogger(EpcUserController.class);

	@Autowired
	private EpcUserService epcUserService;

	@Autowired
	private GroupService groupService;

	@Autowired
	private FileConfig fileConfig;

	/**
	 * 查询
	 * @param request
	 * @param page
	 * @param user
	 * @return
	 */
	@RequestMapping("/ajax/user/getUsers")
	@ResponseBody
	public Map<String,Object> getUsers(HttpServletRequest request, @ModelAttribute("page") PageEntity page, @ModelAttribute("user")EpcUser user){
		Map<String,Object> json = null;
		try{
			List<EpcUser> userList =this.epcUserService.getEpcUserListPage(user,page);
			Map<String,Object> re = new HashMap<>();
			if(userList == null){
				userList = new ArrayList<>();
			}
			re.put("users",userList);
			re.put("page",page);
			json = this.getJsonMap(true, "success", re);
		}catch(Exception e){
			logger.error("EpcUserController.getUsers", e);
			json = this.getJsonMap(false, "failure", null);
		}
		return  json;
	}

	@RequestMapping("/ajax/user/getUserById")
	@ResponseBody
	public Map<String,Object> getUserById(HttpServletRequest request, @ModelAttribute("user") EpcUser user){
		Map<String,Object> json = null;
		try{
			EpcUser user1 =this.epcUserService.getEpcUserById(user);
			json = this.getJsonMap(true, "success", user1);
		}catch(Exception e){
			logger.error("EpcDictController.getDicts", e);
			json = this.getJsonMap(false, "failure", null);
		}
		return  json;
	}

	/**
	 * 新增/修改
	 * @param request
	 * @param user
	 * @return
	 */
	@PostMapping("/ajax/user/saveUser")
	@ResponseBody
	public Map<String,Object> saveUser(HttpServletRequest request, @ModelAttribute("user") EpcUser user) {
		Map<String,Object> json = null;
		try {
			epcUserService.editEpcUser(user);
			json = this.getJsonMap(true, "success", null);
		} catch (Exception e) {
			logger.error("EpcUserController.saveUser", e);
			json = this.getJsonMap(false, "failure", null);
		}
		return  json;
	}
	/***
	 * <b>删除调用的方法</b>
	 * @param ids
	 * @return
	 */
	@PostMapping("/ajax/user/deleteUser")
	@ResponseBody
	public Map<String,Object>  deleteUserBatch(String ids){
		Map<String, Object> json = null;
		try{
			this.epcUserService.deleteEpcUserBatch(ids);
			json = this.getJsonMap(true, "success", null);
		}catch (Exception e){
			logger.error("EpcUserController.deleteUserBatch", e);
			json = this.getJsonMap(false, "failure", null);
		}
		return  json;
	}

	@RequestMapping("/downFile")
	public void downFile(HttpServletRequest request, HttpServletResponse response, String url){
		try{
			if(url != null){
				//File file = new File(FileUtil.rootpath + url);
				File file = new File(fileConfig.getProfile() + url);
				if(file.exists()){
					InputStream inputStream = new FileInputStream(file);
					String fileName = url.substring(url.lastIndexOf("/") + 1,url.length());
					byte[] bytes  = new byte[1024];
					response.setContentType("application/octet-stream");
					response.setHeader("Content-Disposition",
							"attachment;fileName=" +fileName );
					OutputStream out = response.getOutputStream();
					int readTmp = 0;
					//并不是每次都能读到1024个字节，所有用readTmp作为每次读取数据的长度，否则会出现文件损坏的错误
					while ((readTmp = inputStream.read(bytes)) != -1) {
						out.write(bytes, 0, readTmp);
					}
					// 关闭输入流
					inputStream.close();
					out.close();
				}
			}
		}catch(Exception e){

		}
	}

	/***
	 * <b>查询部门信息</b>
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/ajax/user/departments", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> userDepartments(HttpServletRequest request) {
		Map<String, Object> json = null;
		try {
			Long companyId = 0L;
			List<TreeEntity> groupList = this.groupService.getGroupTree("DEPARTMENT", companyId);
			List<TreeEntity> trees = TreeNodeUtil.assembleTree(groupList);
			json = this.getJsonMap(true, "success",trees);
		} catch (Exception e) {
			logger.error("EpcUserController.userDepartments:" + e);
			json = this.getJsonMap(false, "服务器繁忙！", null);
		}
		return json;
	}

	/**
	 * 查询人员状态统计
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/ajax/user/userStatusSatistics", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> userStatusSatistics(HttpServletRequest request) {
		Map<String, Object> json = null;
		try {
			Map<String,Object> res = this.epcUserService.userStatusSatistics();
			json = this.getJsonMap(true, "success",res);
		} catch (Exception e) {
			logger.error("EpcUserController.userStatusSatistics:" + e);
			json = this.getJsonMap(false, "服务器繁忙！", null);
		}
		return json;
	}

	/**
	 * 查询人员扫码次数统计
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/ajax/user/userRecordSatistics", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> userRecordSatistics(HttpServletRequest request, @ModelAttribute("startDate") String startDate,  @ModelAttribute("endDate") String endDate) {
		Map<String, Object> json = null;
		try {
			List<Map<String,Object>> res = this.epcUserService.userRecordSatistics(startDate, endDate);
			json = this.getJsonMap(true, "success",res);
		} catch (Exception e) {
			logger.error("EpcUserController.userStatusSatistics:" + e);
			json = this.getJsonMap(false, "服务器繁忙！", null);
		}
		return json;
	}


	@RequestMapping("/user/export")
	public void courseTotalExport(HttpServletRequest request, @ModelAttribute("user")EpcUser user,HttpServletResponse response) {
		try {
			PageEntity page = new PageEntity();
			page.setPageSize(100);
			List<EpcUser> userList =this.epcUserService.getEpcUserListPage(user,page);
			if(page.getTotalPageSize() > 1){
				for (int i = 2; i <= page.getTotalPageSize() ; i++) {
					page.setCurrentPage(i);
					List<EpcUser> userList1 =this.epcUserService.getEpcUserListPage(user,page);
					userList.addAll(userList1);
				}

			}

			HSSFWorkbook workbook = epcUserService.userExport(userList);

			String fileName = "防疫人员.xls";

			response.addHeader("content-type","application/octet-stream");
			response.addHeader("Content-Disposition","attachment;filename="+toUtf8String(fileName));

			workbook.write(response.getOutputStream());

			workbook.close();

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public static String toUtf8String(String s) {
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < s.length(); i++) {
			char c = s.charAt(i);
			if (c >= 0 && c <= 255) {
				sb.append(c);
			} else {
				byte[] b;
				try {
					b = Character.toString(c).getBytes("utf-8");
				} catch (Exception ex) {
					System.out.println(ex);
					b = new byte[0];
				}
				for (int j = 0; j < b.length; j++) {
					int k = b[j];
					if (k < 0) k += 256;
					sb.append("%" + Integer.toHexString(k).toUpperCase());
				}
			}
		}
		return sb.toString();
	}
}
